package com.esun.payment_api.controller;

import com.esun.common.api.CommonPage;
import com.esun.common.api.CommonResult;
import com.esun.common.utils.BlankUtils;
import com.esun.payment_api.bean.InvProcessBean;
import com.esun.payment_api.bean.SumDkReceiveMoneyBean;
import com.esun.payment_api.dao.FkDraftDao;
import com.esun.payment_api.dao.FkDraftDetail;
import com.esun.payment_api.domain.FkDraft;
import com.esun.payment_api.domain.User;
import com.esun.payment_api.dto.FkDraftQueryParam;
import com.esun.payment_api.dto.PInvInsParam;
import com.esun.payment_api.dto.ProcessApprovalParam;
import com.esun.payment_api.dto.SubmitApprovalParam;
import com.esun.payment_api.service.FkDraftService;
import com.esun.payment_api.service.InvFormService;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import java.math.BigDecimal;
import java.util.List;

import static com.esun.common.utils.JWTUtils.getLoginUser;

/**
 * 汇票付款主表接口
 * Create by hemeichong on 2023-06-12
 */
@RestController
@RequestMapping("/fkDraft")
public class FkDraftController {

    @Resource
    private FkDraftService fkDraftService;

    @Resource
    private InvFormService invFormService;

    @ApiOperation("汇票付款-根据Id返回汇票付款详情，包含相关票据")
    @GetMapping("/getFkDetail")
    @ResponseBody
    public CommonResult<FkDraftDetail> getFkDetail(@RequestParam Integer id) {
        if (BlankUtils.isBlank(id)) {
            return CommonResult.failed("付款id不能为空");
        }
        User user;
        try {
            user = getLoginUser();
        } catch (Exception e) {
            return CommonResult.failed("无法从token中获取用户信息");
        }
        //商承总金额，银承总金额，总金额
        FkDraftDetail fkDraftDetail = fkDraftService.getFkDetail(user, id);
        if (user.getId().equals(fkDraftDetail.getOperatorId())) {
            if ("1".equals(fkDraftDetail.getFlowStatus())) {
                //显示编辑按钮
                fkDraftDetail.setEditable(true);
                //显示保存
                fkDraftDetail.setSaveButton(true);
                //是否展示审批流程
                fkDraftDetail.setIsApprovalProcess(false);
                //显示提交
                fkDraftDetail.setIsSubmit(true);
            } else if ("3".equals(fkDraftDetail.getFlowStatus())) {
                //显示编辑按钮
                fkDraftDetail.setEditable(true);
                //显示保存
                fkDraftDetail.setSaveButton(true);
                //是否展示审批流程
                fkDraftDetail.setIsApprovalProcess(true);
                //显示再次提交
                fkDraftDetail.setIsResubmit(true);
            }
        } else {
            //隐藏编辑按钮
            fkDraftDetail.setEditable(false);
            //隐藏保存按钮
            fkDraftDetail.setSaveButton(false);
        }
        return CommonResult.success(fkDraftDetail);
    }

    @ApiOperation("汇票付款-根据汇票付款类型查询")
    @GetMapping("/getListByType")
    @ResponseBody
    public CommonResult<CommonPage<FkDraftDao>> getListByType(FkDraftQueryParam param,
                                                              @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                              @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {

        FkDraftQueryParam queryParam = new FkDraftQueryParam();

        //筛选：部门名称
        if (!BlankUtils.isBlank(param.getDeptName())) {
            queryParam.setDeptName(param.getDeptName());
        }
        //筛选：审批节点
//        if (!BlankUtils.isBlank(param.getNodeStr())) {
//            queryParam.setNodeStr(param.getNodeStr());
//        }
        //筛选：开始时间-结束时间
        if (!BlankUtils.isBlank(param.getStartTimeStr()) && !BlankUtils.isBlank(param.getEndTimeStr())){
            queryParam.setStartTimeStr(param.getStartTimeStr());
            queryParam.setEndTimeStr(param.getEndTimeStr());
        }
        User user;
        try {
            user = getLoginUser();
        } catch (Exception e) {
            return CommonResult.failed("无法从token中获取登录用户信息");
        }
        if (BlankUtils.isBlank(user.getId())) {
            return CommonResult.failed("登录人id为空");
        }
        if (BlankUtils.isBlank(user.getDeptId())) {
            CommonResult.failed("登录人部门id为空");
        }
        queryParam.setUserId(user.getId());
        queryParam.setDeptId(user.getDeptId());
        queryParam.setCoId(user.getCoId());
        //前后端约定：0-6
        if (!BlankUtils.isBlank(param.getTabStr())) {
            queryParam.setTabStr(param.getTabStr());
            switch (param.getTabStr()) {
                case "0":
                    //全部
                    break;
                case "1":
                    //未提交
                    queryParam.setFlowStatus("1");
                    break;
                case "2":
                    //进行中
                    queryParam.setFlowStatus("2");
                    break;
                case "3":
                    //已通过
                    queryParam.setFlowStatus("4");
                    break;
                case "4":
                    //已拒绝
                    queryParam.setFlowStatus("3");
                    break;
                default:
                    System.out.println("输入参数有误！");
                    break;
            }
        }
        if (!BlankUtils.isBlank(param.getSearchStr())) {
            queryParam.setSearchStr(param.getSearchStr());
        }
        SumDkReceiveMoneyBean sumMoney = fkDraftService.getSumMoneyBySearch(queryParam);

        List<FkDraftDao> list = fkDraftService.getListByType(queryParam, pageSize, pageNum);
        CommonPage<FkDraftDao> fkDraftDaoCommonPage = CommonPage.restPage(list);
        //已兑票据总数
        fkDraftDaoCommonPage.setTotalHp(sumMoney.getHpCount());
        //已兑票据总金额
        fkDraftDaoCommonPage.setTotalInvMoney(sumMoney.getHpTotalMoney());
        return CommonResult.success(fkDraftDaoCommonPage);
    }


    @ApiOperation("汇票付款-根据Id软删除")
    @RequestMapping("/deleteById")
    public CommonResult deleteById(Integer id) {
        try {
            int count = fkDraftService.deleteById(id);
            if (count > 0) {
                return CommonResult.success(count);
            } else {
                return CommonResult.failed("删除失败");
            }
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage());
        }
    }

    @ApiOperation("汇票付款：根据Id删除付款，同时删除关联票据")
    @RequestMapping ("/deleteByIdStr")
    public CommonResult deleteByIdStr(Integer id) {
        PInvInsParam param = new PInvInsParam();
        User user;
        try {
            user = getLoginUser();
        } catch (Exception e) {
            return CommonResult.failed("无法从token中获取登录用户信息");
        }
        if (BlankUtils.isBlank(id)) {
            return CommonResult.failed("付款id不能为空");
        }
        param.setIdStr(id.toString());
        param.setCoId((int) user.getCoId());
        param.setUserId((int) user.getId());
        fkDraftService.deleteByIdStr(param);
        return CommonResult.success("删除付款成功");
    }

    @ApiOperation("汇票付款-更新/保存")
    @PostMapping("/update")
    @ResponseBody
    public CommonResult update(@RequestBody FkDraft fkDraft) {
        if (!BlankUtils.isBlank(fkDraft.getId())) {
            if (fkDraftService.update(fkDraft) == 1) {
                return CommonResult.success("修改成功");
            }
        } else {
            return CommonResult.failed("修改失败,付款id为空");
        }
        return CommonResult.failed("保存失败，请检查数据");
    }

    @ApiOperation("汇票付款-新增并查询新付款信息")
    @PostMapping("/insertReturnId")
    @ResponseBody
    public CommonResult insertReturnId(@RequestBody FkDraft fkDraft) {
        User user;
        try {
            user = getLoginUser();
        } catch (Exception e) {
            return CommonResult.failed("无法从token中获取用户信息");
        }
        fkDraft.setCoId(user.getCoId());
        fkDraft.setCreateBy(user.getId());
        fkDraft.setOperatorId(user.getId());
        fkDraft.setOpDeptId(user.getDeptId());
        //创建数据，并返回实体
        int count = fkDraftService.insertReturnId(fkDraft);
        if (count > 0) {
            Integer fkId = fkDraft.getId();
            System.out.println("获取付款id：" + fkId);
            FkDraft list = fkDraftService.selectByPrimaryKey(fkId);
            return CommonResult.success(list);
        }
        return CommonResult.failed();
    }

    //汇票付款-获取汇票付款审批流程信息
    @ApiOperation("汇票付款-获取汇票付款审批流程信息")
    @GetMapping("/getFkProcess")
    public CommonResult getFkProcess(String uuid) {
        if (BlankUtils.isBlank(uuid)) {
            return CommonResult.failed("UUID不能为空");
        }
        //获取流程审批步骤
        List<InvProcessBean> list = invFormService.getInvProcess(uuid);
        if (list.size() == 0) {
            return CommonResult.failed("获取发起人流程失败");
        }
        return CommonResult.success(list, "获取付款流程页面成功");
    }


    @ApiOperation("汇票付款-提交")
    @RequestMapping("/fkSubmitApproval")
    public CommonResult fkSubmitApproval(@RequestBody SubmitApprovalParam param) {
        User user;
        try {
            user = getLoginUser();
        } catch (Exception e) {
            return CommonResult.failed("无法从token中获取用户信息");
        }
        if (param == null) {
            return CommonResult.failed("请检查输入参数");
        }
        param.setUserId(user.getId());
        param.setDeptId(user.getDeptId());
        param.setCoId(user.getCoId());
        if (BlankUtils.isBlank(param.getUuid())) {
            return CommonResult.failed("UUID不能为空");
        }
        if (BlankUtils.isBlank(param.getFkId())) {
            return CommonResult.failed("付款id不能为空");
        } else {
            String check = fkDraftService.checkFkSubmit(param.getFkId());
            if ("1".equals(check)) {
                try {
                    fkDraftService.fkSubmitApproval(param);
                    return CommonResult.success("提交成功");
                } catch (Exception e) {
                    return CommonResult.failed("提交失败");
                }
            } else {
                return CommonResult.failed(check);
            }
        }
    }

    @ApiOperation("汇票付款-被拒再次提交")
    @RequestMapping("/fkResubmitApproval")
    public CommonResult fkResubmitApproval(@RequestBody SubmitApprovalParam param) {
        User user;
        try {
            user = getLoginUser();
        } catch (Exception e) {
            return CommonResult.failed("无法从token中获取用户信息");
        }
        if (param == null) {
            return CommonResult.failed("请检查输入参数");
        }
        param.setUserId(user.getId());
        param.setDeptId(user.getDeptId());
        param.setCoId(user.getCoId());
        if (BlankUtils.isBlank(param.getUuid())) {
            return CommonResult.failed("UUID不能为空");
        }
        if (BlankUtils.isBlank(param.getFkId())) {
            return CommonResult.failed("付款id不能为空");
        } else {
            String check = fkDraftService.checkFkSubmit(param.getFkId());
            if ("1".equals(check)) {
                try {
                    fkDraftService.fkResubmitApproval(param);
                    return CommonResult.success("重新提交成功");
                } catch (Exception e) {
                    return CommonResult.failed("重新提交失败");
                }
            } else {
                return CommonResult.failed(check);
            }
        }
    }

    @ApiOperation("汇票付款-审批人同意")
    @RequestMapping("/fkProcessApprovalAgree")
    public CommonResult fkProcessApprovalAgree(ProcessApprovalParam param) {
        User user;
        try {
            user = getLoginUser();
        } catch (Exception e) {
            return CommonResult.failed("无法从token中获取用户信息");
        }
        if (param == null) {
            return CommonResult.failed("请检查输入参数");
        }
        param.setUserId(user.getId());
        if (BlankUtils.isBlank(param.getFkId())) {
            return CommonResult.failed("付款id不能为空");
        }
        param.setStatus((short)1);
        System.out.println("flowId：" + param.getFlowId());
        System.out.println("flowNotes：" + param.getFlowNotes());
        System.out.println("userId：" + param.getUserId());
        System.out.println("fkId：" + param.getFkId());
        fkDraftService.fkProcessApproval(param);
        return CommonResult.success("审批同意");
    }

    @ApiOperation("汇票付款-审批人拒绝")
    @RequestMapping("/fkProcessApprovalReject")
    public CommonResult fkProcessApprovalReject(ProcessApprovalParam param) {
        User user;
        try {
            user = getLoginUser();
        } catch (Exception e) {
            return CommonResult.failed("无法从token中获取用户信息");
        }
        if (param == null) {
            return CommonResult.failed("请检查输入参数");
        }
        param.setUserId(user.getId());
        if (BlankUtils.isBlank(param.getFkId())) {
            return CommonResult.failed("付款Id不能为空");
        }
        param.setStatus((short)-1);
        System.out.println("flowId：" + param.getFlowId());
        System.out.println("flowNotes：" + param.getFlowNotes());
        System.out.println("userId：" + param.getUserId());
        System.out.println("fkId：" + param.getFkId());
        fkDraftService.fkProcessApproval(param);
        return CommonResult.success("审批拒绝");
    }
}
